
// This file is part of Module Proxy.

// Module Proxy is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Module Proxy is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Module Proxy.  If not, see <https://www.gnu.org/licenses/>.


//         Copyright (C) 2021 - 2030  关中麦客  
//         All rights reserved
//
//         response.rs
//         常见response状态的封装
//
//         created by 关中麦客 1036038462@qq.com

use hyper::{Body, Response, StatusCode, header};
use bytes::Bytes;
use tokio::io::{AsyncReadExt};
use tokio::fs::File;

/// HTTP status 404
pub async fn rsp_404() -> Response<Body> 
{
    //如果filename以'/'结尾，在后面补上index文件
    let home_path = super::home_path();
    let file_404 = match home_path.ends_with("/")
    {
        true => format!("{}html/{}", home_path, "404.html"),
        false=> format!("{}/html/{}", home_path, "404.html"),
    };

    if let Ok(mut file) = File::open(&file_404).await
    {
        let mut contents = vec![];  //文件内容
        if let Ok(_) = file.read_to_end(&mut contents).await    //读取文件
        {
            if let Ok(rsp) = Response::builder()
                                .status(StatusCode::NOT_FOUND)
                                .header(header::CONTENT_TYPE, "text/html")
                                .header(header::SERVER, super::VERSION)
                                .body(Body::from(contents)) 
            {
                return rsp;
            }
        }
    }

    log::warn!("404.html not exist.");
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .header(header::CONTENT_TYPE, "text/html")
        .header(header::SERVER, super::VERSION)
        .body("Not Found".into())
        .unwrap()
}

/// HTTP status 500
pub async fn rsp_500() -> Response<Body>
{
    //如果filename以'/'结尾，在后面补上index文件
    let home_path = super::home_path();
    let file_500 = match home_path.ends_with("/")
    {
        true => format!("{}html/{}", home_path, "500.html"),
        false=> format!("{}/html/{}", home_path, "500.html"),
    };

    if let Ok(mut file) = File::open(&file_500).await
    {
        let mut contents = vec![];  //文件内容
        if let Ok(_) = file.read_to_end(&mut contents).await    //读取文件
        {
            if let Ok(rsp) = Response::builder()
                                .status(StatusCode::INTERNAL_SERVER_ERROR)
                                .header(header::CONTENT_TYPE, "text/html")
                                .header(header::SERVER, super::VERSION)
                                .body(Body::from(contents)) 
            {
                return rsp;
            }
        }
    }

    log::warn!("500.html not exist.");
    Response::builder()
        .status(StatusCode::INTERNAL_SERVER_ERROR)
        .header(header::CONTENT_TYPE, "text/html")
        .header(header::SERVER, super::VERSION)
        .body("Internal Server Error".into())
        .unwrap()
}

/// Socket response status 200
pub async fn socket_rsp_200(msg: Bytes) -> Response<Body>
{
    if let Ok(body) = String::from_utf8(msg.to_vec())
    {
        if let Ok(rsp) = Response::builder()
                            .status(StatusCode::OK)
                            .header(header::CONTENT_TYPE, "application/json")
                            .header(header::SERVER, super::VERSION)
                            .body(body.into()) 
        {
            return rsp;
        }
    }

    rsp_500().await
}